/**
 * Copyright 2018 人人开源 http://www.renren.io
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package com.hs.srm.base.modules.sys.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.hs.srm.base.common.annotation.DataFilter;
import com.hs.srm.base.common.utils.Constant;
import com.hs.srm.base.common.utils.QueryParam;
import com.hs.srm.base.modules.sys.dao.SysUserDao;
import com.hs.srm.base.modules.sys.entity.SysDeptEntity;
import com.hs.srm.base.modules.sys.entity.SysUserEntity;
import com.hs.srm.base.modules.sys.service.SysDeptService;
import com.hs.srm.base.modules.sys.service.SysUserRoleService;
import com.hs.srm.base.modules.sys.service.SysUserService;
import com.hs.srm.base.modules.sys.shiro.ShiroUtils;
import com.hs.srm.common.utils.PageUtils;

/**
 * 系统用户
 * 
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2016年9月18日 上午9:46:09
 */
@Service("sysUserService")
public class SysUserServiceImpl extends ServiceImpl<SysUserDao, SysUserEntity> implements SysUserService {
	@Autowired
	private SysUserRoleService sysUserRoleService;
	@Autowired
	private SysDeptService sysDeptService;

	@Override
	public List<Long> queryAllMenuId(Long userId) {
		return this.baseMapper.queryAllMenuId(userId);
	}

	@Override
	@DataFilter(subDept = true, user = false)
	public PageUtils queryPage(Map<String, Object> params) {
		String username = (String)params.get("username");
		String name = (String)params.get("name");
		String deptId = (String)params.get("deptId");
		List<Long> deptIdList = new ArrayList<>();
		if(StringUtils.isNotBlank(deptId)) {
			deptIdList.add(new Long(deptId));
			List<Long> subDeptIdList = this.sysDeptService.getSubDeptIdList(new Long(deptId));
			if(!ObjectUtils.isEmpty(subDeptIdList)) {
				deptIdList.addAll(subDeptIdList);
			}
		}

		Page<SysUserEntity> page = this.selectPage(
				new QueryParam<SysUserEntity>(params).getPage(),
				new EntityWrapper<SysUserEntity>()
						.eq(StringUtils.isNotBlank(username), "username", username)
						.like(StringUtils.isNotBlank(name), "name", name)
						.and("user_id!={0} and user_id != {1}", Constant.SUPER_ADMIN, 6)
						.in(!ObjectUtils.isEmpty(deptIdList), "dept_id ", StringUtils.join(deptIdList, ","))
						.addFilterIfNeed(!ObjectUtils.isEmpty(params.get(Constant.SQL_FILTER)),
								(String)params.get(Constant.SQL_FILTER)));

		for(SysUserEntity sysUserEntity : page.getRecords()) {
			SysDeptEntity sysDeptEntity = this.sysDeptService.selectById(sysUserEntity.getDeptId());
			sysUserEntity.setDeptName(sysDeptEntity.getName());
		}

		return new PageUtils(page);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void save(SysUserEntity user) {
		user.setCreateTime(new Date());
		// sha256加密
		String salt = RandomStringUtils.randomAlphanumeric(20);
		user.setSalt(salt);
		user.setPassword(ShiroUtils.sha256(user.getPassword(), user.getSalt()));
		this.insert(user);

		// 保存用户与角色关系
		this.sysUserRoleService.saveOrUpdate(user.getUserId(), user.getRoleIdList());
	}

	@Override
	@DataFilter(subDept = true, user = true)
	public List<SysUserEntity> selectDataFilterUserList(Map<String, Object> params) {
		return this.baseMapper.selectList(new EntityWrapper<SysUserEntity>().addFilterIfNeed(
				!ObjectUtils.isEmpty(params.get(Constant.SQL_FILTER)), (String)params.get(Constant.SQL_FILTER)));
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void update(SysUserEntity user) {
		/*if(StringUtils.isBlank(user.getPassword())){
			user.setPassword(null);
		}else{
			user.setPassword(ShiroUtils.sha256(user.getPassword(), user.getSalt()));
		}*/
		this.updateById(user);

		// 保存用户与角色关系
		this.sysUserRoleService.saveOrUpdate(user.getUserId(), user.getRoleIdList());
	}

	@Override
	public boolean updatePassword(Long userId, String password, String newPassword) {
		SysUserEntity userEntity = new SysUserEntity();
		userEntity.setPassword(newPassword);
		return this.update(userEntity, new EntityWrapper<SysUserEntity>().eq("user_id", userId)
				.eq("password", password));
	}

	@Override
	public Long userPost(Long userId) {
		return this.baseMapper.selectUserPost(userId);
	}

}
